﻿using Bootstrap5.Abstractions;
using System;

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;

namespace Bootstrap5;

[HtmlTag("input")]
public abstract class FormInputBase<TValue> :FormControlBase<TValue>
{
	protected abstract string Type { get; }
	/// <summary>
	/// The event to call the two-way binding callback. Default is <see cref="Event.OnInput"/>.
	/// </summary>
	[Parameter] public Event ChangeEvent { get; set; } = Event.OnInput;
	protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        if (CascadedFloating is not null)
        {
            BuildInput(builder);
            BuildLabel(builder);
        }
        else
        {
            BuildLabel(builder);
            BuildInput(builder);
        }
    }

    protected virtual void BuildInput(RenderTreeBuilder builder)
    {
        builder.OpenRegion(100);
        builder.OpenElement(0, GetHtmlTagName());
        builder.AddAttribute(1, "type", Type);
        builder.AddAttribute(2, "id", FieldId);
        builder.AddAttribute(3, "value", CurrentValueAsString);
        builder.AddAttribute(4, "name", FieldIdentifier.FieldName);
        builder.AddAttribute(5, ChangeEvent.Value, EventCallback.Factory.CreateBinder(this, __value => CurrentValue = __value, CurrentValue));
        BuildCommonAttributes(builder);
        builder.CloseElement();
        builder.CloseRegion();
    }
}
